package org.elepower.realms;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.elepower.dao.FunctionDao;
import org.elepower.dao.UserDao;
import org.elepower.pojo.PsFunction;
import org.elepower.pojo.PsUser;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    private UserDao userDao;

    private FunctionDao functionDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setFunctionDao(FunctionDao functionDao) {
        this.functionDao = functionDao;
    }

    //用户授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        PsUser user = (PsUser) principalCollection.getPrimaryPrincipal();

        List<PsFunction> list = functionDao.getPerByUserId(user.getId());
        Set<String> set = new HashSet<>();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(set);
        return info;
    }

    /**
     * 用户认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取subject（主体），其实就是登陆用户 的 身份信息，也就是用户名、手机号、邮箱
        String principal = (String) token.getPrincipal();

        PsUser user = userDao.getByUserName(principal);

        //如果身份信息不正确，返回null，shiro会自动抛出UnkonwAccountExcpetion
        if (user == null){
            return null;
        }else if(user.getUserState() == 1){
            //抛出用户被锁定异常
            throw new LockedAccountException();
        }
        return new SimpleAuthenticationInfo(user,user.getPassword(),ByteSource.Util.bytes(user.getSalt()),"heiha");
    }
}
